<template>
  <div class="app-container">
    <el-button size="small" v-if="datalist.length == 0" type="primary" @click="addspecific">添加规格组</el-button>
    <div class="specifications" :key="'e' + index1" v-for="(item1, index1) in datalist">
      <div class="specific_top">
        <el-select class="select" :key="index1" size="small" @change="selectchange($event, index1)" v-model="item1.selectvalue" placeholder="请选择">
          <el-option v-for="(item2,index2) in item1.options" :key="index2" :label="item2.label" :value="item2.value" :disabled="item2.disabled"></el-option>
        </el-select>

        <el-checkbox class="checkbox" v-model="item1.checked" :key="'a' + index1">是否关联</el-checkbox>

        <el-select
          v-show="item1.checked"
          @change="selectchangearr($event, index1)"
          class="select"
          size="medium"
          v-model="datalist[index1].selectvalues"
          multiple
          collapse-tags
          :key="'b' + index1"
          placeholder="请选择"
        >
        <el-option v-for="item3 in item1.options" :key="item3.value" :label="item3.label" :value="item3.value" :disabled="item3.disabled"></el-option>
        </el-select>

        <el-checkbox v-show="item1.checked" class="checkbox" v-model="item1.ismust" :key="'c' + index1">是否是必选项</el-checkbox>

        <div class="delete_btn">
          <el-button class="delete" :key="'d' + index1" size="small" type="danger" @click="deletespecific(index1)">删除</el-button>
          <el-button class="delete" :key="'f' + index1" size="small" type="primary" @click="addspecific" v-if="datalist.length - 1 == index1">添加</el-button>
        </div>
      </div>
      <div class="specific_top">
        <div class="specific_list">
            <div class="specific_item" v-for="(item5, index5) in item1.zum" :key="'f' + index5">
                <template v-for="(item6,index6) in item5">
                    <span :key="'g'+index6">{{ item6.name }}：</span>
                    <el-input :key="'f'+index6" size="small" class="input" v-model="item6.opts" placeholder="请输入"></el-input>
                </template>
                <el-button class="btn_delete" size="small" type="danger" @click="deletecur(index1,index5)">删除</el-button>
            </div>
        </div>
      </div>
    </div>
    <div class="submit_btn" v-if="datalist.length !== 0">
        <el-button class="subbtn" type="primary" @click="generatedform">确认</el-button>
    </div>
    <div class="last_data">
        <el-table
            :data="tableData"
            :span-method="objectSpanMethod"
            border
            style="width: 100%; margin-top: 20px">
            <el-table-column v-for="(item,index) in tableData" :key="index"
                :prop="item.prop"
                :label="item.label"
                width="180">
            </el-table-column>
        </el-table>
    </div>
  </div>
</template>

<script>
export default {
  filters: {
    curselectarr() {}
  },
data() {
    return {
        list: null,
        listLoading: true,
        datalist: [],
        zum:[],
        tableData: [{
            prop:"id",
            label:"ID",
            id: '12987123',
            name: '王小虎',
            amount1: '165',
            amount2: '4.43',
            amount3: 12
        }, {
            prop:"name",
            label:"姓名",
            id: '12987123',
            name: '王小虎',
            amount1: '165',
            amount2: '4.43',
            amount3: 12
        }, {
            prop:"amount1",
            label:"数值一",
            id: '12987124',
            name: '王小虎',
            amount1: '324',
            amount2: '1.9',
            amount3: 9
        }, {
            prop:"amount2",
            label:"数值二",
            id: '12987125',
            name: '王小虎',
            amount1: '621',
            amount2: '2.2',
            amount3: 17
        }, {
            prop:"amount3",
            label:"数值三",
            id: '12987126',
            name: '王小虎',
            amount1: '539',
            amount2: '4.1',
            amount3: 15
        }]
    };
},
  created() {
    //   this.addspecific();
    // var _this = this;
    // // 规格组合总数 (table行数)
    // var totalRow = 1;
    // for (var i = 0; i < _this.spec_attr.length; i++) {
    //     totalRow *= _this.spec_attr[i].spec_items.length;
    // }
    // // 遍历tr 行
    // var specList = [];
    // for (i = 0; i < totalRow; i++) {
    //     var rowData = [], rowCount = 1, specSkuIdAttr = [];
    //     // 遍历td 列
    //     for (var j = 0; j < _this.spec_attr.length; j++) {
    //         var skuValues = _this.spec_attr[j].spec_items;
    //         rowCount *= skuValues.length;
    //         var anInterBankNum = (totalRow / rowCount)
    //             , point = ((i / anInterBankNum) % skuValues.length);
    //         if (0 === (i % anInterBankNum)) {
    //             rowData.push({
    //                 rowspan: anInterBankNum,
    //                 item_id: skuValues[point].item_id,
    //                 spec_value: skuValues[point].spec_value
    //             });
    //         }
    //         specSkuIdAttr.push(skuValues[parseInt(point.toString())].item_id);
    //     }
    //     specList.push({
    //         spec_sku_id: specSkuIdAttr.join('_'),
    //         rows: rowData,
    //         form: {}
    //     });
    // }
    // // return false;
    // // 合并旧sku数据
    // if (_this.spec_list.length > 0 && specList.length > 0) {
    //     for (i = 0; i < specList.length; i++) {
    //         var overlap = _this.spec_list.filter(function (val) {
    //             return val.spec_sku_id === specList[i].spec_sku_id;
    //         });
    //         if (overlap.length > 0) specList[i].form = overlap[0].form;
    //     }
    // }

    // _this.spec_list = specList;
  },
  computed: {},
  watch: {
    // datalist:{
    //     deep: true,
    //     handler: function (newVal){

    //     }
    // }
  },
  methods: {
    // 合并计算方法
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex % 2 === 0) {
            if (columnIndex === 0) {
            return [1, 2];
            } else if (columnIndex === 1) {
            return [0, 0];
            }
        }
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
            return {
                rowspan: 2,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    }
    },
    // 数据克隆
    deepClone(source) {
        if (!source && typeof source !== 'object') {
            throw new Error('error arguments', 'deepClone')
        }
        const targetObj = source.constructor === Array ? [] : {}
        Object.keys(source).forEach(keys => {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = this.deepClone(source[keys])
            } else {
                targetObj[keys] = source[keys]
            }
        })
        return targetObj
    },
    // 监听下拉框改变
    selectchange(e, index) {
        // index 当前项下标
        this.datalist[index].options.forEach(ele => {
            // 当前选择项禁选
            if (ele.value == this.datalist[index].selectvalue) {
                ele.disabled = true;
            } else {
                ele.disabled = false;
            }
        });
        // 清空当前关联项
        this.datalist[index].selectvalues = '';
        this.datalist[index].k_ruledata = [];

        if(this.datalist[index].selectvalue){
            let curselectarr = [this.datalist[index].selectvalue].concat(this.datalist[index].selectvalues);
            let newcurselectarr = [];
            console.log(curselectarr);
            this.datalist[index].options.forEach(e=>{
                curselectarr.forEach(i=>{
                    if(e.value == i){
                        newcurselectarr.push({
                            k_rule_name:e.label,
                            k_moreruledata:e.k_moreruledata
                        })
                    }
                })
            });
            console.log(newcurselectarr);
            this.datalist[index].k_ruledata = newcurselectarr;
            let data = this.datalist[index].k_ruledata;
            console.log(data);
            // 先清除zum规格
            this.datalist[index].zum = [];
            this.datalist[index].k_ruledata.forEach(item=>{
                this.getDate(this.datalist[index].zum,item,index);
            })
            this.datalist[index].zum.forEach(item=>{
            console.log(item);
            item.push({
                name:"价格",
                opts:"0",
                type:1,
            })
        })
        }
    },
    getDate(zum,first,curindex){
        //公共存的集合  第一个集合
        if(zum.length!=0){
            let item = first.k_moreruledata;
            console.log(item);
            let zumto=[];
            for(let index in zum){
                for(let to in item){
                    let ss = [];
                    // 添加之前的数据
                    ss.push(
                        ...zum[index]
                    );
                    // 添加属性名
                    ss.push({
                        name:first.k_rule_name,
                        opts:item[to].rule_name,
                    });
                    zumto.push(ss);
                }
            }

            this.datalist[curindex].zum = this.deepClone(zumto);

        }else{
            let item = first.k_moreruledata;
            console.log(item);
            let zumto=[];
            for(let index in item){
                console.log(item[index]);
                let ss = [];
                ss.push({
                    name:first.k_rule_name,
                    opts:item[index].rule_name,
                })
                zumto.push(ss);
            }
            this.datalist[curindex].zum = zumto;
        }
    },
    selectchangearr(e, index) {
        if (this.datalist[index].selectvalues.length > -1) {
            let curselectarr = [this.datalist[index].selectvalue].concat(this.datalist[index].selectvalues);
            let newcurselectarr = [];
            console.log(curselectarr);
            this.datalist[index].options.forEach(e=>{
                curselectarr.forEach(i=>{
                    if(e.value == i){
                        newcurselectarr.push({
                            k_rule_name:e.label,
                            k_moreruledata:e.k_moreruledata
                        })
                    }
                })
            });
        console.log(newcurselectarr);
        this.datalist[index].k_ruledata = newcurselectarr;
        let data = this.datalist[index].k_ruledata;
        console.log(data);

        // 先清除zum规格
        this.datalist[index].zum = [];
        this.datalist[index].k_ruledata.forEach(item=>{
            this.getDate(this.datalist[index].zum,item,index);
        })
        this.datalist[index].zum.forEach(item=>{
            console.log(item);
            item.push({
                name:"价格",
                opts:"0",
                type:1,
            })
        })
        console.log(this.datalist[index].zum);
      }
    },
    // 添加新规格
    addspecific() {
      this.datalist.push({
        options: [
          {
            value: '1',
            label: '尺寸',
            data: ['200'],
            k_rule_name:'尺寸',
            k_moreruledata:[
                { rule_id: '11', rule_name: "200"},
                { rule_id: '22', rule_name: "300"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '2',
            label: '重量',
            k_rule_name:'重量',
            data: ['500', '600'],
            k_moreruledata:[
                { rule_id: '11', rule_name: "500"},
                { rule_id: '22', rule_name: "600"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '3',
            label: '颜色',
            k_rule_name:'颜色',
            data: ['green','blue'],
            k_moreruledata:[
                { rule_id: '11', rule_name: "color1"},
                { rule_id: '22', rule_name: "color2"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '4',
            label: '尺码',
            data: ['200'],
            k_rule_name:'尺码',
            k_moreruledata:[
                { rule_id: '11', rule_name: "大"},
                { rule_id: '22', rule_name: "小"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '5',
            label: '型号',
            data: ['x','y'],
            k_rule_name:'型号',
            k_moreruledata:[
                { rule_id: '11', rule_name: "xxl"},
                { rule_id: '22', rule_name: "xl"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '6',
            label: '纸张',
            data: ['白卡纸'],
            k_rule_name:'纸张',
            k_moreruledata:[
                { rule_id: '11', rule_name: "白卡纸1"},
                { rule_id: '22', rule_name: "白卡纸2"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '7',
            label: '款式',
            k_rule_name:'款式',
            data: ['款式二','款式一'],
            k_moreruledata:[
                { rule_id: '11', rule_name: "款式二"},
                { rule_id: '22', rule_name: "款式一"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '8',
            label: '材质',
            k_rule_name:'材质',
            data: ['金的','银的'],
            k_moreruledata:[
                { rule_id: '11', rule_name: "金的"},
                { rule_id: '22', rule_name: "银的"},
            ],
            disabled: false // 禁用当前值
          },
          {
            value: '9',
            label: '类型',
            k_rule_name:'类型',
            data: ['111','222'],
            k_moreruledata:[
                { rule_id: '11', rule_name: "111"},
                { rule_id: '22', rule_name: "222"},
            ],
            disabled: false // 禁用当前值
          }
        ], // 数据
        selectvalue: '', // 单选
        selectvalues: '', // 多选
        checked: false, // 是否关联
        ismust: false, // 是否必选
        curselectarr: [

        ], //当前规格数据
        k_ruledata:[
            {
                k_rule_id:'id',
                k_rule_name:'尺寸',
                k_rule:false,
                k_provaluse:'属性名',//属性
                k_moreruledata:[
                   { rule_id: '11', rule_name: "大"},
                   { rule_id: '22', rule_name: "二"},
                   { rule_id: '22', rule_name: "三"},
                ],
            }
        ],
        zum:[]
      });
    },
    // 删除当前规格组
    deletespecific(index) {
        this.$confirm('是否删除该规格组, 是否继续?', '提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.$delete(this.datalist, index);
            this.$message({
                type: 'success',
                message: '删除成功!'
            })
        }).catch(() => {});
    },
    // 删除当前规格条
    deletecur(index1,index2){
        this.$delete(this.datalist[index1].zum,index2);
            this.$message({
            message: '规格删除成功',
            type: 'success'
        })
    },
    getDate2(zum,first){
        console.log(zum);
        //公共存的集合  第一个集合
        let item;
        if(zum.length!=0){
            item = this.zum;
        }else{
            item = this.datalist[0].zum;
        };
        let zumto = [];
        for(let index in item){
            for(let to in first){
                let ss = [];
                // 添加之前的数据
                ss.push(
                    ...item[index]
                );
                ss.forEach((e,idx)=>{
                    if(e.newnum == 0 || e.newnum){
                        this.$delete(ss,idx)
                    }
                })
                // 添加属性名
                ss.push(
                    ...first[to]
                );

                // 计算价格
                let newnum = 0;
                ss.forEach((item,index)=>{
                    if(item.type){
                        newnum += ss[index].opts * 1;
                    }
                });
                ss.push({
                    name:"基础价",
                    newnum:newnum
                });

                zumto.push(ss);
            }
        };
        console.log(zumto);
        this.zum = zumto;
    },
    // 生成表格
    generatedform(){
        this.zum = [];
        this.datalist.forEach((item,index)=>{
            if(index>0){
                this.getDate2(this.zum,item.zum)
            }
        })
    }
  }
};
</script>
<style lang="css">
.specifications {
  position: relative;
  margin: 20px;
  display: flex;
  flex-direction: column;
}
.specific_top {
  width: 100%;
}

.specific_list {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  background-color: aliceblue;
}

.input {
  width: 80px;
}

.specific_item {
  margin: 10px 15px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 16px;
}
.specific_item span{
    margin: 10px 15px;
}
.checkbox {
  margin: 15px;
}
.select {
  margin: 15px;
}
.delete_btn {
  height: 60px;
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
}
.delete {
  margin: 14px;
}

.btn_delete{
    padding: 8px 2px;
    margin-left: 20px;
}
.submit_btn{
    width: 100%;
    display: flex;
    justify-content: center;
}
.subbtn{
    margin: 25px;
    width: 150px;
}
</style>
